﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Concurrency;
using System.Threading.Tasks;

using alib.Debugging;
using alib.Enumerable;

namespace agree
{
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	///
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	public class TaskController : identity_base
	{
		public TaskController(IIdentity prv, IScheduler _sch)
			: base(prv)
		{
			this.scheduler = _sch ?? TaskPoolScheduler.Default;
		}

		IScheduler scheduler;
		public IScheduler Scheduler
		{
			get { return scheduler ?? ((IRtParent)trace).TaskControl.Scheduler; }
			set { scheduler = value; }
		}

		IScheduler ui_scheduler;
		public IScheduler UiScheduler
		{
			get { return ui_scheduler ?? ((IRtParent)trace).TaskControl.UiScheduler; }
			set { ui_scheduler = value; }
		}


		public void ParallelLoop<T>(IEnumerable<T> ie, Action<T> a)
		{
			if (scheduler is CurrentThreadScheduler)
				foreach (T t in ie)
					a(t);
			else
				Parallel.ForEach(ie, a);
		}

		public ParallelQuery<T> AsParallel<T>(IEnumerable<T> seq)
		{
			var z = System.Linq.ParallelEnumerable.AsParallel(seq);
			return scheduler is CurrentThreadScheduler ? z.WithDegreeOfParallelism(1) : z;
		}
	};
}
